package com.hliu.core.dao.mybatis;

import com.hliu.core.dao.IBaseMybatisDao;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * author: 6
 * date: 13-4-9
 */
public abstract class BaseMybatisDao<T extends Serializable, PK extends Serializable> extends SqlSessionDaoSupport implements IBaseMybatisDao<T, PK> {
	Logger logger = LoggerFactory.getLogger(BaseMybatisDao.class);
	private Class<T> clazz;

	protected BaseMybatisDao(Class<T> clazz) {
		this.clazz = clazz;
	}

	protected BaseMybatisDao() {
		this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	protected String getStatement(String queryKey) {
		return this.clazz.getName() + "." + queryKey;
	}

	@Override
	public T get(String queryKey, PK id) {
		return (T)getSqlSession().selectOne(getStatement(queryKey), id);
	}

	@Override
	public T load(String queryKey, PK id) {
		return get(queryKey, id);
	}

	@Override
	public void save(String queryKey, T t) {
		getSqlSession().insert(getStatement(queryKey), t);
	}

	@Override
	public void update(String queryKey, T t) {
		getSqlSession().update(getStatement(queryKey), t);
	}

	@Override
	public List<T> list(String queryKey) {
		return getSqlSession().selectList(getStatement(queryKey));
	}

	@Override
	public void deleteObject(String queryKey, T t) {
		getSqlSession().delete(getStatement(queryKey), t);
	}

	@Override
	public void delete(String queryKey, PK id) {
		getSqlSession().delete(getStatement(queryKey), id);
	}
}
